package com.dianrui.qiyouriding.util;

import java.security.MessageDigest;

public class MD5 {
	
	/**
	 * @FieldName: DEFAULT_CHARSET
	 * @FieldType: String
	 * @Description: 默认字符集格式
	 */
	private static final String DEFAULT_CHARSET = "utf-8";
	
	/**
	 * @FieldName: hexDigits
	 * @FieldType: String[]
	 * @Description: 全局数组
	 */
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	/**
	 * @Title: digest
	 * @Description: 摘要
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String digest(String data) throws Exception{
		return digest(data, DEFAULT_CHARSET);
	}
	
	/**
	 * @Title: digest
	 * @Description: 摘要
	 * @param data
	 * @param charset 字符编码
	 * @return
	 * @throws Exception
	 */
	public static String digest(String data, String charset) throws Exception {
		String result = null;
		if(!isEmpty(data) ){
			try {
				byte[] bytes = MessageDigest.getInstance("MD5").digest(data.getBytes(charset));
				result = byteToString(bytes);
				System.out.println("MD5摘要成功");
			} 
			catch (Exception e) {
				String err = "MD5摘要错误[{0}]";
				System.out.println(err);
			}
		}
		return result;
	}
	
	/**
	 * @Title: byteToArrayString
	 * @Description: 返回形式为数字跟字符串
	 * @param bByte
	 * @return
	 */
	private static String byteToArrayString(byte bByte) {
		int iRet = bByte;
		if (iRet < 0) {
			iRet += 256;
		}
		int iD1 = iRet / 16;
		int iD2 = iRet % 16;
		return hexDigits[iD1] + hexDigits[iD2];
	}

//	/**
//	 * @Title: byteToNum
//	 * @Description: 返回形式只为数字
//	 * @param bByte
//	 * @return
//	 */
//	private static String byteToNum(byte bByte) {
//		int iRet = bByte;
//		if (iRet < 0) {
//			iRet += 256;
//		}
//		return String.valueOf(iRet);
//	}

	/**
	 * @Title: byteToString
	 * @Description: 转换字节数组为16进制字串
	 * @param bByte
	 * @return
	 */
	private static String byteToString(byte[] bByte) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < bByte.length; i++) {
			sb.append(byteToArrayString(bByte[i]));
		}
		return sb.toString();
	}

	public static boolean isEmpty(String s) {
		return s == null || s.equals("") || s.toUpperCase().equals("NULL") || s.equals("undefined");
	}
}
